extends PanoramaSky

class_name BallanceSky

export(int) var width: int = 2048
export(int) var height: int = 1024
export(String) var sky_name: String
export(Color) var default_color: Color = Color(0.0, 0.0, 0.0, 1.0)
export(bool) var estimate_color: bool = true
export(float) var sky_energy: float = 0.6
export(float) var sun_angle_max: float = 100.0
export(float) var sun_angle_min: float = 1.0
export(Color) var sun_color: Color = Color(1.0, 1.0, 1.0, 1.0)
export(float) var sun_energy: float = 1.0
export(float, EASE) var sun_curve: float = 0.05
export(float) var sun_latitude: float = 35.0
export(float) var sun_longitude: float = 0.0

func generate(output_png = null):
	if panorama != null:
		return

	if resource_path != "" and not resource_local_to_scene:
		if ResourceLoader.has_cached(resource_path + "::panorama"):
			panorama = ResourceLoader.load(resource_path + "::panorama")
			return

	var fns: Array = []

	for s in ["Left", "Right", "Down", null, "Front", "Back"]:
		if s == null:
			fns.append(null)
		else:
			fns.append("res://texture/ballance/Sky/Sky_%s_%s.png.binary" % [sky_name, s])

	var ctp: CubemapToPanorama = CubemapToPanorama.new()

	for i in 6:
		var img = null
		var fn = fns[i]
		if fn != null:
			var f: File = File.new()
			if f.open(fn, File.READ) == OK:
				f.seek_end()
				var sz: int = f.get_position()
				f.seek(0)
				img = Image.new()
				if img.load_png_from_buffer(f.get_buffer(sz)) != OK:
					img = null
			if img == null:
				push_error("Failed to load '%s'" % fn)
		ctp.cubemap.append(img)

	ctp.default_color = default_color
	ctp.estimate_color = estimate_color

	ctp.cubemap_to_panorama(width, height, [
		sky_energy,
		deg2rad(sun_angle_max),
		deg2rad(sun_angle_min),
		Color(sun_color.r * sun_energy, sun_color.g * sun_energy, sun_color.b * sun_energy, sun_color.a),
		sun_curve,
		deg2rad(sun_latitude),
		deg2rad(sun_longitude),
	])

	if output_png != null:
# warning-ignore:return_value_discarded
		ctp.panorama.save_png(output_png)

	var tex: ImageTexture = ImageTexture.new()
	tex.create_from_image(ctp.panorama)

	panorama = tex

	if resource_path != "" and not resource_local_to_scene:
		panorama.take_over_path(resource_path + "::panorama")
